const cloud = require('@cloudbase/node-sdk')

// 初始化云开发实例
const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV
})

// 获取数据库引用
const db = app.database()
const collection = db.collection('recommend_template')

/**
 * recommend_template CRUD 云函数
 * @param {Object} event - 云函数参数
 * @param {Object} context - 云函数上下文
 */
exports.main = async (event, context) => {
    const { action, data } = event

    try {
        // 操作日志
        console.log('recommend-template-crud 调用:', { action, data })

        switch (action) {
            case 'create':
                return await createTemplate(data)
            case 'read':
                return await getTemplate(data)
            case 'update':
                return await updateTemplate(data)
            case 'delete':
                return await deleteTemplate(data)
            case 'list':
                return await listTemplates(data)
            default:
                throw new Error('无效的操作类型')
        }
    } catch (error) {
        console.error('recommend-template-crud 错误:', error)
        return {
            code: -1,
            message: error.message,
            data: null
        }
    }
}

// 创建推荐模板
async function createTemplate(data) {
    const { fileid, fileidPdf, id, imgPreview, tags, template, title, enable } = data

    if (!template || !title) {
        throw new Error('模板内容和标题为必填项')
    }

    const result = await collection.add({
        fileid: fileid || '',
        fileidPdf: fileidPdf || '',
        id: id || '',
        imgPreview: imgPreview || '',
        tags: tags || '',  // 注意：tags 是字符串，用逗号分隔
        template,
        title,
        enable: enable === false ? false : true, // 默认为启用状态
        createdAt: new Date(),
        updatedAt: new Date()
    })

    return {
        code: 0,
        message: '创建成功',
        data: result
    }
}

// 获取单个模板
async function getTemplate(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).get()

    if (!result.data || result.data.length === 0) {
        throw new Error('模板不存在')
    }

    return {
        code: 0,
        message: '查询成功',
        data: result.data[0]
    }
}

// 更新模板
async function updateTemplate(data) {
    const { _id, fileid, fileidPdf, id, imgPreview, tags, template, title, enable } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const updateData = {
        updatedAt: new Date()
    }

    if (fileid !== undefined) updateData.fileid = fileid
    if (fileidPdf !== undefined) updateData.fileidPdf = fileidPdf
    if (id !== undefined) updateData.id = id
    if (imgPreview !== undefined) updateData.imgPreview = imgPreview
    if (tags !== undefined) updateData.tags = tags
    if (template) updateData.template = template
    if (title) updateData.title = title
    if (enable !== undefined) updateData.enable = enable

    const result = await collection.doc(_id).update(updateData)

    return {
        code: 0,
        message: '更新成功',
        data: result
    }
}

// 删除模板
async function deleteTemplate(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).remove()

    return {
        code: 0,
        message: '删除成功',
        data: result
    }
}

// 获取模板列表
async function listTemplates(data) {
    const { page = 1, pageSize = 10, id, title, tags, enable } = data

    let query = collection.where({})

    // 使用 command 对象进行高级查询
    const cmd = db.command

    // 构建查询条件
    const conditions = {}

    if (id) {
        conditions.id = db.RegExp({
            regexp: id,
            options: 'i',
        })
    }

    if (title) {
        conditions.title = db.RegExp({
            regexp: title,
            options: 'i',
        })
    }

    if (tags) {
        conditions.tags = db.RegExp({
            regexp: tags,
            options: 'i',
        })
    }

    // 处理启用状态筛选
    if (enable !== undefined) {
        if (enable === true) {
            // 启用状态：enable 字段为 true 或不存在
            conditions._id = cmd.exists(true) // 确保记录存在
            conditions.enable = cmd.or([true, cmd.exists(false)])
        } else if (enable === false) {
            // 禁用状态：enable 字段明确为 false
            conditions.enable = false
        }
    }

    // 应用所有查询条件
    if (Object.keys(conditions).length > 0) {
        query = query.where(conditions)
    }

    const result = await query
        .orderBy('createdAt', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    const countResult = await query.count()

    return {
        code: 0,
        message: '查询成功',
        data: {
            list: result.data,
            total: countResult.total,
            page,
            pageSize
        }
    }
}